const form = document.querySelector('form')
const oldpwd = document.querySelector('.oldPassword')
const newpwd = document.querySelector('.newPassword')
const rnewpwd = document.querySelector('.rnewPassword')

const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')


//是否登录验证及获取个人信息
testLogin()
function testLogin(){
    if (!id || !token) return window.location.href = './login.html'

    ajax({
        url: 'http://localhost:8888/users/info',
        data: 'id=' + id,
        headers: { authorization: token },
        dataType: 'json',
        success (res) {
          // 当 res.code 不是 1 的时候, 跳转回到登录页
          if (res.code !== 1) return window.location.href = 'login.html'
        }
      })
}


form.addEventListener('submit', e=>{
    e = e || window.event
    try{e.preventDefault()}catch (err){e.returnValue = false}
    const info = {
        id:id,
        oldPassword:oldpwd.value,
        newPassword:newpwd.value,
        rNewPassword:rnewpwd.value 
    }
    if(!info.oldPassword || !info.newPassword || !info.rNewPassword){
        return layer.alert('请完整填写', {
            skin: 'layui-layer-lan'
            ,closeBtn: 0
            ,anim: 2//动画类型
          });
    }
    if(info.newPassword !== info.rNewPassword){
        return layer.msg('两次输入密码不一致')
    }
    ajax({
        url:'http://localhost:8888/users/rpwd',
        method:'post',
        data:querystringify(info),
        headers:{ authorization: token },
        dataType:'json',
        success(res){
            if(res.code ===1){
                layer.msg('修改密码成功, 需要重新登录 ',{
                    icon:1,
                    time:2000
                },()=>{
                    window.location.href = 'login.html'
                })
           }
            if(res.code !== 1){
               return layer.msg('修改密码失败，请检查原密码');
            }
        }
    })
   
})